package com.itheima.service.impl;

import com.itheima.common.entity.Result;
import com.itheima.common.utils.DateUtils;
import com.itheima.common.utils.SMSUtils;
import com.itheima.dto.SubmitOrderDTO;
import com.itheima.mapper.UserMemberMapper;
import com.itheima.mapper.UserOrderMapper;
import com.itheima.mapper.UserOrderSettingMapper;
import com.itheima.mapper.UserSetmealMapper;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.Setmeal;
import com.itheima.service.UserOrderService;
import com.itheima.vo.OrderVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

@Service
public class UserOrderServiceImpl implements UserOrderService {
    private static final Logger log = LoggerFactory.getLogger(UserOrderServiceImpl.class);
    /**
     * 体检预约
     * @param submitOrderDTO
     */
    @Autowired
    private UserOrderSettingMapper userOrderSettingMapper;
    @Autowired
    private UserMemberMapper userMemberMapper;
    @Autowired
    private UserOrderMapper userOrderMapper;
    @Autowired
    private UserSetmealMapper userSetmealMapper;
    @Override
    public void submitOrder(SubmitOrderDTO submitOrderDTO) {
         String errorString =null;
        OrderSetting orderSetting = new OrderSetting();
        //查询预约表这天是否存在
        orderSetting = userOrderSettingMapper.orderSettingExitByOrderDate(submitOrderDTO.getOrderDate());
        if (Objects.isNull(orderSetting)) {
            errorString="所选日期不存在，请联系相关人员";
            log.error(errorString);
            throw  new RuntimeException(errorString);
        }
        //查询人数是否满员
        orderSetting = userOrderSettingMapper.orderSettingNumberAndReservations(submitOrderDTO.getOrderDate());
        if (orderSetting.getReservations()>=orderSetting.getNumber()){
             errorString="当天预约人数以满，请选择其他日期";
             log.error(errorString);
             throw  new RuntimeException(errorString);
        }
        //查询用户是否存在，存在检查该用户是否重复预约(通过预约时间和用户id查询和套餐)，若不存在则自动注册用户
        Member member = userMemberMapper.memberExit(submitOrderDTO.getTelephone());
        if (!Objects.isNull(member)){
            Integer memberId = member.getId();
            Date orderDate = submitOrderDTO.getOrderDate();
            Integer setmealId = submitOrderDTO.getSetmealId();
            //查询是否重复预约
             Order order= userOrderMapper.orderExit(orderDate,memberId,setmealId);
             //如果没有重复预约则添加这次预约
            if (!Objects.isNull(order)){
                errorString="请勿重复预约";
                log.error(errorString);
                throw new RuntimeException(errorString);
            }
        }else {
            Member addMember = Member.builder()
                    .idCard(submitOrderDTO.getIdCard())
                    .name(submitOrderDTO.getName())
                    .regTime(submitOrderDTO.getOrderDate())
                    .sex(submitOrderDTO.getSex())
                    .phoneNumber(submitOrderDTO.getTelephone())
                    .build();
            userMemberMapper.insertMember(addMember);
        }
        //获得memberid
        Integer memberId = member.getId();
        Order addOrder=Order.builder()
                .memberId(memberId)
                .orderDate(submitOrderDTO.getOrderDate())
                .orderType(Order.ORDERTYPE_WEIXIN)
                .orderStatus(Order.ORDERSTATUS_NO)
                .setmealId(submitOrderDTO.getSetmealId())
                .build();
        //给预约表添加预约信息
        userOrderMapper.insertOrder(addOrder);
        //更新当天预约人数,当天预约人数加1
        orderSetting.setReservations(orderSetting.getReservations()+1);
        userOrderSettingMapper.updateOrderSetting(orderSetting);
        //发送短信
        try {
            SMSUtils.sendMessage(SMSUtils.ORDER_NOTICE,submitOrderDTO.getTelephone(),DateUtils.parseDate2String(submitOrderDTO.getOrderDate()));
        } catch (Exception e) {
            errorString="验证码发送失败";
            log.error(errorString);
            throw new RuntimeException(errorString);
        }


    }

    /**
     *根据预约id查询预约信息
     * @param id
     * @return
     */
    @Override
    public OrderVO findById(String id) {
        Integer checkid = Integer.parseInt(id);
        //orders表查询
        Order order=userOrderMapper.findById(checkid);
        //判断order表是否存在
        if(Objects.isNull(order)){
            log.error("id：{}查询的表，不存在",id);
            throw new RuntimeException("请输入正确的id");
        }
        //根据order类中的memberId查询对应的members表的name
       Member member = userMemberMapper.findById(order.getMemberId());
       //根据order类中的setmealId查询对应的表的name
        Setmeal setmeal = userSetmealMapper.findById(order.getSetmealId());
        try {
            String orderVODate  = DateUtils.parseDate2String(order.getOrderDate());
            OrderVO orderVO = OrderVO.builder()
                    .member(member.getName())
                    .orderDate(orderVODate)
                    .orderType(order.getOrderType())
                    .setmeal(setmeal.getName())
                    .build();
            return orderVO;
        } catch (Exception e) {
            throw new RuntimeException("请输入很正确的时间格式");
        }
    }
}
